package com.life.wd.service.Imp;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.life.wd.dto.GoodsAddRequest;
import com.life.wd.dto.GoodsQueryRequest;
import com.life.wd.dto.GoodsUpdateRequest;
import com.life.wd.entity.Goods;
import com.life.wd.mapper.GoodsMapper;
import com.life.wd.mapper.ProductMapper;
import com.life.wd.result.PageResult;
import com.life.wd.service.GoodsService;
import jakarta.transaction.Transactional;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private ProductMapper productMapper;

    @Override
    public Long addGoods(GoodsAddRequest request) throws IOException {
        // 验证关联的产品是否存在
        validateProductExists(request.getGoodsId());

        // 构建商品实体
        Goods goods = new Goods();
        goods.setTitle(request.getTitle());
        goods.setDesc(request.getDesc());
        goods.setContent(request.getContent());
        goods.setPrice(request.getPrice().doubleValue());
        goods.setGoodsId(request.getGoodsId());

        // 处理上传的图片
        MultipartFile file = request.getImageFile();
        if (file != null && !file.isEmpty()) {
            goods.setImageUrl(file.getBytes());
            goods.setContentType(file.getContentType());
        }

        // 插入数据库
        goodsMapper.insert(goods);

        return goods.getId();
    }

    // 验证产品存在性
    private void validateProductExists(Long productId) {
        // 实际实现中调用ProductService验证产品是否存在
        if (productMapper.getById(productId) == null) {
            throw new IllegalArgumentException("关联的产品不存在，ID: " + productId);
        }
    }

    @Override
    public PageResult listGoods(GoodsQueryRequest request) {
        // 设置分页参数
        PageHelper.startPage(request.getPage(), request.getPageSize());

        // 执行查询
        Page<Goods> goodsList = goodsMapper.listGoods(request);

        return new PageResult(goodsList.getTotal(), goodsList.getResult());
    }

    @Override
    public boolean updateGoods(GoodsUpdateRequest request) throws IOException {
        // 验证商品是否存在
        Goods goods = goodsMapper.getById(request.getId());
        if (goods == null) {
            throw new IllegalArgumentException("商品不存在，ID: " + request.getId());
        }

        // 更新商品信息（仅更新有值的字段）
        if (request.getTitle() != null) {
            goods.setTitle(request.getTitle());
        }

        if (request.getDesc() != null) {
            goods.setDesc(request.getDesc());
        }

        if (request.getContent() != null) {
            goods.setContent(request.getContent());
        }

        if (request.getPrice() != null) {
            goods.setPrice(request.getPrice().doubleValue());
        }

        if (request.getGoodsId() != null) {
            // 验证新关联的产品是否存在
            validateProductExists(request.getGoodsId());
            goods.setGoodsId(request.getGoodsId());
        }

        // 处理上传的图片（如果有）
        MultipartFile file = request.getImageFile();
        if (file != null && !file.isEmpty()) {
            goods.setImageUrl(file.getBytes());
            goods.setContentType(file.getContentType());
        }

        // 更新数据库
        int rows = goodsMapper.update(goods);
        return rows > 0;
    }

    @Override
    public boolean deleteGoods(Long id) {
        // 验证商品是否存在
        if (goodsMapper.getById(id) == null) {
            throw new IllegalArgumentException("商品不存在，ID: " + id);
        }

        // 执行删除操作
        int rows = goodsMapper.delete(id);
        return rows > 0;
    }

    @Override
    @Transactional // 保证批量删除的原子性
    public boolean deleteGoodsBatch(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return false;
        }

        int total = ids.size();
        int deleted = goodsMapper.deleteBatch(ids);
        return deleted == total;
    }
}